// 用于拼接字符串（自动插入换行）并替换到代码文件的类
function myString(dfText) {
  this.val = dfText || "";
  this.add = (text) => (this.val += (text || "") + "\r\n");
  this.writeTo = (strCode, tag) => {
    return strCode.replace(new RegExp(`\\$\\$${tag},?`, "g"), this.val.trimLeft());
  };
}

import { getQueryComponents } from "./getFormComponents";

export const generatorIndex = (setting, temp) => {
  let strCode = temp;
  temp = null;

  const { page, formInfo, dbTable, db } = setting;

  console.log("page.btns", page.btns);

  const leftTree = page.left;
  const apiIndex = db.find((item) => item.apiType == 0);
  const apiDel = db.find((item) => item.apiType == 4);
  // 获取表单字段
  const fileds = [];
  const filedMap = {};
  formInfo.tabList.forEach((tab) => {
    fileds.push(
      ...tab.components.filter((t) => !["gridtable", "divider", "btn", "card", "viewtable"].includes(t.type))
    );
  });
  fileds.forEach((item) => {
    filedMap[item.prop] = item;
  });

  // 获取主表信息
  const mainTable = dbTable.find((t) => t.type == "main");
  // 获取主表主键
  const mainKey = mainTable.columns.find((t) => t.isPrimary) || {};
  // 新增按钮
  const addBtn = page.btns.find((t) => t.id == "Add");

  const dataOptions = [];

  console.log(window.$lowerFirst("FPCWxx"), "mainKey");

  strCode = strCode.replace(new RegExp(`\\$\\$MAINKEY?`, "g"), window.$lowerFirst(mainKey.name));
  strCode = strCode.replace(new RegExp(`\\$\\$MODULECODE,?`, "g"), `${setting.moduleId}_${setting.name}`);

  // 表单弹窗处理
  if (formInfo.openType != "2") {
    strCode = strCode.replace(new RegExp(`\\$\\$DIALOGWRAPER,?`, "g"), "dialog");
    strCode = strCode.replace("$$DIALOGHEIGHT", formInfo.dialogHeight || 400);
    strCode = strCode.replace("$$DIALOGWIDTH", formInfo.dialogWidth || 600);
  } else {
    strCode = strCode.replace(new RegExp(`\\$\\$DIALOGWRAPER,?`, "g"), "drawer");
    strCode = strCode.replace("$$DIALOGWIDTH", formInfo.drawerWidth || 600);
    strCode = strCode.replace(':height="$$DIALOGHEIGHT"', "");
  }

  // 生成左侧树形
  let TEMPLATELEFT = new myString();
  if (page.layoutType == 2) {
    TEMPLATELEFT.add("        <template #left>");
    if (leftTree.dataType == "2") {
      // 如果是数据字典，则生成一个数据字典管理功能页
      TEMPLATELEFT.add(`            <l-panel style="padding-right:0;" >`);
      TEMPLATELEFT.add(`                <template #title>`);
      TEMPLATELEFT.add(`                    {{$t('表单分类')}}`);
      TEMPLATELEFT.add(`                    <div class="tree-setting-btn" >`);
      TEMPLATELEFT.add(`                        <el-tooltip effect="dark" :content="$t('分类管理')" placement="top">`);
      TEMPLATELEFT.add(
        `                            <el-button @click="handleSettingClick" type="text" icon="el-icon-setting"></el-button>`
      );
      TEMPLATELEFT.add(`                        </el-tooltip>`);
      TEMPLATELEFT.add(`                    </div>`);
      TEMPLATELEFT.add(`                </template>`);
    } else {
      TEMPLATELEFT.add(`            <l-panel :title="$t('${leftTree.title}')" style="padding-right:0;" >`);
    }
    TEMPLATELEFT.add(
      `                <el-tree v-loading="treeLoading" :data="treeData" default-expand-all :expand-on-click-node="false"  @node-click="handleNodeClick">`
    );
    TEMPLATELEFT.add(`                    <span class="lr-tree-node"  slot-scope="{node}">`);
    TEMPLATELEFT.add(`                        {{ $t(node.label) }}`);
    TEMPLATELEFT.add(`                    </span>`);
    TEMPLATELEFT.add(`                </el-tree>`);
    TEMPLATELEFT.add(`            </l-panel>`);
    TEMPLATELEFT.add("        </template>");
  }
  strCode = TEMPLATELEFT.writeTo(strCode, "TEMPLATELEFT");
  TEMPLATELEFT = null;

  // 中心部分（主要是表格）
  let TEMPLATECENTER = new myString();

  if (page.queryType == "2") {
    // 查询布局风格二
    strCode = strCode.replace(new RegExp(`\\$\\$TOP,?`, "g"), `:top="queryHeight + 12"`);

    TEMPLATECENTER.add(`        <template #top >`);
    if (page.layoutType == 2) {
      TEMPLATECENTER.add(`            <l-panel style="padding-bottom:0;padding-left:0;">`);
    } else {
      TEMPLATECENTER.add(`            <l-panel style="padding-bottom:0;">`);
    }

    //TEMPLATECENTER.add(`            <l-panel style="padding-bottom:0;">`)
    TEMPLATECENTER.add(
      `                <l-query :items="queryItems" :height.sync="queryHeight" :formData="queryData" :loading="tableLoading" @search="handleSearch">`
    );
    page.table.querys.forEach((item) => {
      let queryProp = "";
      if (mainTable.name == filedMap[item.id].table) {
        queryProp = window.$lowerFirst(filedMap[item.id].field);
      } else {
        queryProp = `${window.$lowerFirst(filedMap[item.id].table)}_${filedMap[item.id].field}`;
      }
      //console.log(filedMap[item.id].type)
      //console.log(filedMap[item.id])
      if (["modifytime", "createtime", "datetime"].includes(filedMap[item.id].type)) {
        queryProp += `QRange`;
      }
      TEMPLATECENTER.add(`                    <template #${queryProp} >`);
      // 添加表单组件
      TEMPLATECENTER.add(getQueryComponents(filedMap[item.id], queryProp, "                        "));

      TEMPLATECENTER.add(`                    </template>`);

      if (
        ["radio", "checkbox", "select", "selectMultiple", "treeselect", "layerselect"].includes(filedMap[item.id].type)
      ) {
        dataOptions.push(filedMap[item.id]);
      }
    });
    TEMPLATECENTER.add(`                </l-query>`);
    TEMPLATECENTER.add(`            </l-panel>`);
    TEMPLATECENTER.add(`        </template>`);
  }

  if (page.layoutType == 2) {
    if (page.queryType == "1") {
      TEMPLATECENTER.add(`        <l-panel style="padding-left:0;" >`);
    } else {
      TEMPLATECENTER.add(`        <l-panel style="padding-left:0;padding-top:0;" >`);
    }
  } else {
    if (page.queryType == "1") {
      TEMPLATECENTER.add(`        <l-panel>`);
    } else {
      TEMPLATECENTER.add(`        <l-panel style="padding-top:0;">`);
    }
  }

  if (page.queryType == "1") {
    // 查询布局风格1
    strCode = strCode.replace(new RegExp(`\\$\\$TOP,?`, "g"), ``);
    // 查询条件
    TEMPLATECENTER.add(`            <template #toolLeft >`);
    TEMPLATECENTER.add(
      `                <l-query2 :items="queryItems" :formData="queryData" :loading="tableLoading" @search="handleSearch">`
    );
    page.table.querys.forEach((item) => {
      let queryProp = "";
      if (mainTable.name == filedMap[item.id].table) {
        queryProp = window.$lowerFirst(filedMap[item.id].field);
      } else {
        queryProp = `${window.$lowerFirst(filedMap[item.id].table)}_${filedMap[item.id].field}`;
      }
      //console.log(filedMap[item.id].type)
      //console.log(filedMap[item.id])
      if (["modifytime", "createtime", "datetime"].includes(filedMap[item.id].type)) {
        queryProp += `QRange`;
      }
      TEMPLATECENTER.add(`                    <template #${queryProp} >`);
      // 添加表单组件
      TEMPLATECENTER.add(getQueryComponents(filedMap[item.id], queryProp, "                        "));

      TEMPLATECENTER.add(`                    </template>`);

      if (
        ["radio", "checkbox", "select", "selectMultiple", "treeselect", "layerselect"].includes(filedMap[item.id].type)
      ) {
        dataOptions.push(filedMap[item.id]);
      }
    });
    TEMPLATECENTER.add(`                </l-query2>`);
    TEMPLATECENTER.add("            </template>");
    // 按钮
    TEMPLATECENTER.add(`            <template #toolRight >`);

    if (addBtn != undefined) {
      let icon = addBtn.icon == "el-icon-plus" ? "" : `btnIcon="${addBtn.icon}"`;
      TEMPLATECENTER.add(
        `                <l-tool-btns ${icon} :hasTableSetting="true" @setting="lr_handleSettingTable" @click="handleAdd()" >`
      );
    } else {
      TEMPLATECENTER.add(
        `                <l-tool-btns :hasTableSetting="true" @setting="lr_handleSettingTable" :hasAdd="false" >`
      );
    }
    let _btns = page.btns.filter((t) => !["Add", "Import"].includes(t.id) && !t.notHtml && !t.isRowBtn);
    if (_btns.length > 0) {
      TEMPLATECENTER.add(`                    <el-button-group>`);
      _btns.forEach((btn) => {
        TEMPLATECENTER.add(
          `                        <el-button v-if="lr_hasPageAuth('${btn.prop}','buttons')" size="mini" icon="${
            btn.icon
          }" @click="handle${window.$upFirst(btn.prop)}()">${btn.label}</el-button>`
        );
      });
      TEMPLATECENTER.add(`                    </el-button-group>`);
    }
    TEMPLATECENTER.add(`                    <l-excel-btns></l-excel-btns>`);
    TEMPLATECENTER.add(`                </l-tool-btns>`);
    TEMPLATECENTER.add("            </template>");
  } else {
    // 查询布局风格二
    TEMPLATECENTER.add(`            <template #toolLeft >`);
    TEMPLATECENTER.add(`                <div class="l-panel--item" >`);
    page.btns
      .filter((t) => !t.notHtml && !t.isRowBtn)
      .forEach((btn) => {
        TEMPLATECENTER.add(
          `                    <el-button v-if="lr_hasPageAuth('${
            btn.prop
          }','buttons')" type="primary" size="mini" icon="${btn.icon}" @click="handle${window.$upFirst(btn.prop)}()">${
            btn.label
          }</el-button>`
        );
      });
    TEMPLATECENTER.add(`                </div>`);
    TEMPLATECENTER.add(`                <div class="l-panel--item" >`);
    TEMPLATECENTER.add(`                    <l-excel-btns></l-excel-btns>`);
    TEMPLATECENTER.add(`                </div>`);

    TEMPLATECENTER.add("            </template>");
    TEMPLATECENTER.add(`            <template #toolRight >`);
    TEMPLATECENTER.add(
      `                <l-tool-btns :hasTableSetting="true" @setting="lr_handleSettingTable" :hasAdd="false" >`
    );
    TEMPLATECENTER.add(`                </l-tool-btns>`);
    TEMPLATECENTER.add("            </template>");
  }

  // 添加主表格
  TEMPLATECENTER.add(`            <l-table `);
  TEMPLATECENTER.add(`                ref="mainTable" `);
  TEMPLATECENTER.add(`                :loading="tableLoading" `);
  TEMPLATECENTER.add(`                :columns="lr_getPageColumns(columns)" `);
  TEMPLATECENTER.add(`                :dataSource="tableData"`);
  if (page.table.isPage) {
    // 判断是否分页
    TEMPLATECENTER.add(`                :isPage="true"`);
    TEMPLATECENTER.add(`                :pageTotal="tableTotal"`);
    TEMPLATECENTER.add(`                :tablePage.sync="tableCurrentPage"`);
    TEMPLATECENTER.add(`                @loadPageData="turnTablePage"`);
  }
  TEMPLATECENTER.add(`                >`);
  TEMPLATECENTER.add(
    `                <template v-for="(col,index) in lr_tableColumnsByToLabel(lr_getPageColumns(columns))" v-slot:[col.prop]="scope" >`
  );
  TEMPLATECENTER.add(`                    <l-value-to-label`);
  TEMPLATECENTER.add(`                    :value="scope.row[col.prop]"`);
  TEMPLATECENTER.add(`                    :type="col.dataType"`);
  TEMPLATECENTER.add(`                    :code="col.dataCode"`);
  TEMPLATECENTER.add(`                    :valueKey="col.valueKey"`);
  TEMPLATECENTER.add(`                    :labelKey="col.labelKey"`);
  TEMPLATECENTER.add(`                    :options="col.options"`);
  TEMPLATECENTER.add(`                    :format="col.format"`);
  TEMPLATECENTER.add(`                    :setting="col.setting"`);
  TEMPLATECENTER.add(`                    :key="index" ></l-value-to-label>`);
  TEMPLATECENTER.add(`                </template>`);

  let _rowBtns = page.btns.filter((t) => !t.notHtml && t.isRowBtn);
  if (_rowBtns.length > 0) {
    TEMPLATECENTER.add(
      `                <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>`
    );
  }
  TEMPLATECENTER.add(`            </l-table>`);

  TEMPLATECENTER.add(`        </l-panel>`);
  strCode = TEMPLATECENTER.writeTo(strCode, "TEMPLATECENTER");
  TEMPLATECENTER = null;

  // 需要导入的包
  let IMPORT = new myString();

  IMPORT.add(`    import queryString  from 'query-string'`);

  let TEMPLATEDATAITEM = new myString();
  let COMPONENTS = new myString();
  if (page.layoutType == 2 && leftTree.dataType == "2") {
    //IMPORT.add(`    import dataitemDetailIndex from '@/views/data/dataItem/detailindex'`)

    //COMPONENTS.add(`dataitemDetailIndex`)

    TEMPLATEDATAITEM.add(`        <l-drawer`);
    TEMPLATEDATAITEM.add(`            :title="$t('分类管理')"`);
    TEMPLATEDATAITEM.add(`            :visible.sync="classifysVisible"`);
    TEMPLATEDATAITEM.add(`            :showOk="false"`);
    TEMPLATEDATAITEM.add(`            :showClose="false"`);
    TEMPLATEDATAITEM.add(`            :width="800"`);
    TEMPLATEDATAITEM.add(`            >`);
    TEMPLATEDATAITEM.add(`            <l-dataitem-index classifyCode="${leftTree.dataCode}"></l-dataitem-index>`);
    TEMPLATEDATAITEM.add(`        </l-drawer>`);
  }
  strCode = COMPONENTS.writeTo(strCode, "COMPONENTS");
  COMPONENTS = null;
  strCode = TEMPLATEDATAITEM.writeTo(strCode, "TEMPLATEDATAITEM");
  TEMPLATEDATAITEM = null;

  IMPORT.add(`    const api = window.$api.${setting.moduleId.toLowerCase()}.${window.$lowerFirst(setting.name)}`);

  strCode = IMPORT.writeTo(strCode, "IMPORT");
  IMPORT = null;

  // 树形固定数据

  let LEFTTREEDATA = new myString();
  let LEFTTREECOMPUTED = new myString();
  let LEFTTREEINIT = new myString();
  let LEFTTREEMETHODS = new myString();
  if (page.layoutType == 2) {
    LEFTTREEDATA.add(`                // 左侧树形数据参数`);
    LEFTTREEDATA.add(`                treeLoading:false,`);
    LEFTTREEDATA.add(`                treeCategory:'',`);

    LEFTTREECOMPUTED.add(`            // 左侧树形数据参数`);
    LEFTTREECOMPUTED.add(`            treeData(){`);
    switch (leftTree.dataType) {
      case "1":
        // 1.静态数据
        LEFTTREECOMPUTED.add(`                return ${JSON.stringify(leftTree.options)}`);
        break;
      case "2":
        // 2.数据字典数据
        LEFTTREEDATA.add(`                classifysVisible:false,`);

        LEFTTREECOMPUTED.add(`                return this.lr_dataItemTree(this.lr_dataItem['${leftTree.dataCode}'])`);

        LEFTTREEINIT.add(`                this.lr_loadDataItem('${leftTree.dataCode}')`);

        LEFTTREEMETHODS.add(`            handleSettingClick(){`);
        LEFTTREEMETHODS.add(`                this.classifysVisible = true`);
        LEFTTREEMETHODS.add(`            },`);

        break;
      case "3":
        // 3.数据源数据
        LEFTTREECOMPUTED.add(
          `                return this.lr_DataSourceTree(this.lr_dataSourceData['${leftTree.dataCode}'],'${leftTree.dataIdKey}','${leftTree.dataPIdKey}','${leftTree.dataValueKey}','${leftTree.dataLabelKey}')`
        );
        LEFTTREEINIT.add(`                this.lr_loadDataSourceData('${leftTree.dataCode}')`);
        break;
      case "4":
        // 4.接口数据源
        LEFTTREECOMPUTED.add(
          `                return this.lr_DataSourceTree(this.lr_apiDataSourceData['${leftTree.apiCode}'],'${leftTree.dataIdKey}','${leftTree.dataPIdKey}','${leftTree.dataValueKey}','${leftTree.dataLabelKey}')`
        );
        LEFTTREEINIT.add(`                this.lr_loadApiDataSourceData('${leftTree.apiCode}','${leftTree.apiUrl}')`);
        break;
    }

    LEFTTREECOMPUTED.add(`            },`);

    LEFTTREEMETHODS.add(`            handleNodeClick(node) {`);
    LEFTTREEMETHODS.add(`                this.treeCategory = node.value`);
    if (page.table.isPage) {
      LEFTTREEMETHODS.add(`                this.loadTableData(true)`);
    } else {
      LEFTTREEMETHODS.add(`                this.loadTableData()`);
    }

    LEFTTREEMETHODS.add(`            },`);
  }

  LEFTTREEINIT.add(`                this.loadTableData()`);

  strCode = LEFTTREEDATA.writeTo(strCode, "LEFTTREEDATA");
  LEFTTREEDATA = null;
  strCode = LEFTTREECOMPUTED.writeTo(strCode, "LEFTTREECOMPUTED");
  LEFTTREECOMPUTED = null;
  strCode = LEFTTREEINIT.writeTo(strCode, "LEFTTREEINIT");
  LEFTTREEINIT = null;
  strCode = LEFTTREEMETHODS.writeTo(strCode, "LEFTTREEMETHODS");
  LEFTTREEMETHODS = null;

  // 表格
  let TABLEDATA = new myString();
  if (page.table.isPage) {
    // 判断是否分页
    TABLEDATA.add(`                tableTotal:0,`);
    TABLEDATA.add(`                tableCurrentPage:1,`);
    TABLEDATA.add(`                tablePageSize:50,`);
  }
  TABLEDATA.add(`                columns: [`);
  page.table.columns.forEach((col) => {
    const colItem = filedMap[col.id];
    let colProp = "";
    if (mainTable.name == colItem.table) {
      colProp = window.$lowerFirst(colItem.field);
    } else {
      colProp = `${window.$lowerFirst(colItem.table)}_${colItem.field}`;
    }
    const _width = col.isMinWidth ? `minWidth:${col.width}` : `width:${col.width}`;
    let point = `                    {label:'${col.label}',prop:'${colProp}',${_width},align:'${col.align}'`;
    if (["radio", "checkbox", "select", "selectMultiple", "treeselect", "layerselect"].includes(colItem.type)) {
      switch (colItem.dataType) {
        case "1":
          point += `,dataType:'mydata',options:${JSON.stringify(colItem.options)}`;
          break;
        case "2":
          point += `,dataType:'dataItem',dataCode:'${colItem.dataCode}'`;
          break;
        case "3":
          point += `,dataType:'dataSource',dataCode:'${colItem.dataCode}',valueKey:'${colItem.dataValueKey}',labelKey:'${colItem.dataLabelKey}'`;
          break;
      }
    } else if (["datetime", "createtime", "modifytime"].includes(colItem.type)) {
      point += `,dataType:'datetime',format:'${colItem.format || "yyyy-MM-dd HH:mm:ss"}'`;
    } else if (["upload"].includes(colItem.type)) {
      point += `,dataType:'file'`;
    } else if (["uploadimg"].includes(colItem.type)) {
      point += `,dataType:'img'`;
    } else if (["companySelect", "company"].includes(colItem.type)) {
      point += `,dataType:'company'`;
    } else if (["departmentSelect", "department"].includes(colItem.type)) {
      point += `,dataType:'department'`;
    } else if (["userSelect", "createuser", "modifyuser"].includes(colItem.type)) {
      point += `,dataType:'user'`;
    } else if (["rate", "switch"].includes(colItem.type)) {
      const colItem2 = window.$deepClone(colItem);
      delete colItem2.type;
      delete colItem2.label;
      delete colItem2.span;
      delete colItem2.display;
      delete colItem2.disabled;
      delete colItem2.default;
      delete colItem2.table;
      delete colItem2.field;
      delete colItem2.prop;
      point += `,dataType:'${colItem.type}',setting:${JSON.stringify(colItem2)}`;
    } else if (["areaselect"].includes(colItem.type)) {
      point += `,dataType:'areas'`;
    } else {
      point += `,dataType:'${colItem.type}'`;
    }
    point += "},";

    TABLEDATA.add(point);

    //TABLEDATA.add(`                    {label:'${col.label}',prop:'${colProp}',${_width},align:'${col.align}'},`)
  });
  TABLEDATA.add(`                ],`);
  if (_rowBtns.length > 0) {
    TABLEDATA.add(`                tableBtns:[`);
    _rowBtns.forEach((btn) => {
      TABLEDATA.add(`                    {prop:'${btn.prop}',label:'${btn.label}'},`);
    });
    TABLEDATA.add(`                ],`);
  }
  strCode = TABLEDATA.writeTo(strCode, "TABLEDATA");
  TABLEDATA = null;

  let TABLEMETHODS = new myString();
  if (page.table.isPage) {
    TABLEMETHODS.add(`            handleSearch(){`);
    TABLEMETHODS.add(`                this.loadTableData()`);
    TABLEMETHODS.add(`            },`);
    TABLEMETHODS.add(`            turnTablePage({rows}){`);
    TABLEMETHODS.add(`                this.tablePageSize = rows`);
    TABLEMETHODS.add(`                this.loadTableData(true)`);
    TABLEMETHODS.add(`            },`);

    TABLEMETHODS.add(`            async loadTableData(isNotFirst){`);
    TABLEMETHODS.add(`                if(!isNotFirst){`);
    TABLEMETHODS.add(`                    this.tableCurrentPage = 1`);
    TABLEMETHODS.add(`                }`);
    TABLEMETHODS.add(`                this.tableLoading = true`);
    TABLEMETHODS.add(`                let queryData = this.$deepClone(this.queryData)`);
    TABLEMETHODS.add(`                $$$DATETIMEQUERY`);
    TABLEMETHODS.add(`                queryData.rows = this.tablePageSize`);
    TABLEMETHODS.add(`                queryData.page = this.tableCurrentPage`);
    let sidx = mainTable.columns[0].name;
    if (page.table.sidx) {
      if (mainTable.name == filedMap[page.table.sidx].table) {
        sidx = window.$lowerFirst(filedMap[page.table.sidx].field);
      } else {
        sidx = `${window.$lowerFirst(filedMap[page.table.sidx].table)}_${filedMap[page.table.sidx].field}`;
      }
    }

    if (page.table.isDESC) {
      sidx += " DESC";
    }

    TABLEMETHODS.add(`                queryData.sidx = '${sidx}'`);

    if (page.layoutType == 2) {
      let treeColItem = filedMap[leftTree.colField];
      let treeColProp = "";
      if (mainTable.name == treeColItem.table) {
        treeColProp = window.$lowerFirst(treeColItem.field);
      } else {
        treeColProp = `${window.$lowerFirst(treeColItem.table)}_${treeColItem.field}`;
      }
      TABLEMETHODS.add(`                queryData.${treeColProp} = this.treeCategory`);
    }

    TABLEMETHODS.add(
      `                let data = await this.$awaitWraper(this.$http.request({url:"${apiIndex.f_Url}",method:"${apiIndex.f_RequestMethod}",data:queryData,params:queryData }))`
    );
    TABLEMETHODS.add(`                if(data != null){`);
    TABLEMETHODS.add(`                    this.tableData = data.rows`);
    TABLEMETHODS.add(`                    this.tableTotal = data.records`);
    TABLEMETHODS.add(`                }`);
    TABLEMETHODS.add(`                else{`);
    TABLEMETHODS.add(`                    this.tableData = []`);
    TABLEMETHODS.add(`                }`);
    TABLEMETHODS.add(`                this.tableLoading = false`);
  } else {
    TABLEMETHODS.add(`            hanleSearch(){`);
    TABLEMETHODS.add(`                this.loadTableData()`);
    TABLEMETHODS.add(`            },`);
    TABLEMETHODS.add(`            loadTableData(){`);
    TABLEMETHODS.add(`                this.tableLoading = true`);
    TABLEMETHODS.add(`                let queryData = this.$deepClone(this.queryData)`);
    TABLEMETHODS.add(`                $$$DATETIMEQUERY`);

    if (page.layoutType == 2) {
      let treeColItem = filedMap[leftTree.colField];
      let treeColProp = "";
      if (mainTable.name == treeColItem.table) {
        treeColProp = window.$lowerFirst(treeColItem.field);
      } else {
        treeColProp = `${window.$lowerFirst(treeColItem.table)}_${treeColItem.field}`;
      }
      TABLEMETHODS.add(`                queryData.${treeColProp} = this.treeCategory`);
    }

    TABLEMETHODS.add(
      `                let data = await this.$awaitWraper(this.$http.request({url:"${apiIndex.f_Url}",method:"${apiIndex.f_RequestMethod}",data:queryData,params:queryData }))`
    );
    TABLEMETHODS.add(`                this.tableData = data || []`);
    TABLEMETHODS.add(`                this.tableLoading = false`);
  }
  TABLEMETHODS.add(`            },`);
  strCode = TABLEMETHODS.writeTo(strCode, "TABLEMETHODS");
  TABLEMETHODS = null;

  // 查询数据
  let QUERYDATA = new myString();
  let QUERY2DATA = new myString();
  let DATETIMEQUERY = new myString();
  if (page.queryType == "2") {
    QUERYDATA.add(`                queryHeight:44,`);
  }

  QUERYDATA.add(`                queryData:{`);
  QUERY2DATA.add(`                queryItems:[`);
  page.table.querys.forEach((item) => {
    let queryProp = "";
    if (mainTable.name == filedMap[item.id].table) {
      queryProp = window.$lowerFirst(filedMap[item.id].field);
    } else {
      queryProp = `${window.$lowerFirst(filedMap[item.id].table)}_${filedMap[item.id].field}`;
    }

    if (["modifytime", "createtime", "datetime"].includes(filedMap[item.id].type)) {
      queryProp += `QRange`;
    }
    if (["rate", "slider"].includes(filedMap[item.id].type)) {
      QUERYDATA.add(`                    ${queryProp}:0,`);
    } else {
      QUERYDATA.add(`                    ${queryProp}:'',`);
    }
    QUERY2DATA.add(`                    {label:'${filedMap[item.id].label}',prop:'${queryProp}'},`);
  });
  QUERYDATA.add(`                },`);
  QUERY2DATA.add(`                ],`);
  strCode = QUERYDATA.writeTo(strCode, "QUERYDATA");
  QUERYDATA = null;
  strCode = QUERY2DATA.writeTo(strCode, "QUERY2DATA");
  QUERY2DATA = null;
  strCode = DATETIMEQUERY.writeTo(strCode, "DATETIMEQUERY");
  DATETIMEQUERY = null;

  // 按钮方法
  let BTNSMETHODS = new myString();
  page.btns
    .filter((t) => !t.notHtml)
    .forEach((btn) => {
      switch (btn.id) {
        case "Add":
          BTNSMETHODS.add(`            handleAdd(){`);
          BTNSMETHODS.add(`                this.formEdit = false`);
          BTNSMETHODS.add(`                this.handleShowForm()`);
          BTNSMETHODS.add(`            },`);
          break;
        case "Edit":
          BTNSMETHODS.add(`            handleEdit($index,row){`);
          BTNSMETHODS.add(`                this.formEdit = true`);
          BTNSMETHODS.add(`                this.formEditRow = row`);
          BTNSMETHODS.add(`                this.handleShowForm()`);
          BTNSMETHODS.add(`            },`);
          break;
        case "Delete":
          BTNSMETHODS.add(`            handleDelete($index,row){`);
          BTNSMETHODS.add(
            `                this.$confirm(this.$t('此操作将永久删除该数据, 是否继续?'), this.$t('提示'), {`
          );
          BTNSMETHODS.add(`                confirmButtonText: this.$t('确定'),`);
          BTNSMETHODS.add(`                cancelButtonText: this.$t('取消'),`);
          BTNSMETHODS.add(`                type: 'warning'`);
          BTNSMETHODS.add(`                }).then(async () => {`);

          BTNSMETHODS.add(
            `                    await this.$http.request({url:"${apiDel.f_Url}/"+row.${window.$lowerFirst(
              mainKey.name
            )},method:"${apiDel.f_RequestMethod}", })`
          );
          BTNSMETHODS.add(`                    this.tableData.splice($index,1);`);
          if (page.table.isPage) {
            BTNSMETHODS.add(`                    this.tableTotal--`);
          }

          BTNSMETHODS.add(`                    this.$message({`);
          BTNSMETHODS.add(`                        type: 'success',`);
          BTNSMETHODS.add(`                        message: this.$t('删除成功!')`);
          BTNSMETHODS.add(`                    })`);
          BTNSMETHODS.add(`                }).catch(() => {`);
          BTNSMETHODS.add(`                    this.$message({`);
          BTNSMETHODS.add(`                        type: 'info',`);
          BTNSMETHODS.add(`                        message: this.$t('已取消删除!')`);
          BTNSMETHODS.add(`                    })`);
          BTNSMETHODS.add(`                })`);
          BTNSMETHODS.add(`            },`);
          break;
        case "Export":
          BTNSMETHODS.add(`            handleExport(){`);
          BTNSMETHODS.add(
            `                const loading = this.$loading({
            lock: true,
            text: "文件导出中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });`
          );
          BTNSMETHODS.add(`       const exportParams = { ...this.$deepClone(this.queryData), rows: 99999, page: 1 };`);
          BTNSMETHODS.add(`     let urlParams =  queryString.stringify(exportParams);`);
          BTNSMETHODS.add(`    const params = {
            fileName: new Date().getTime()+"",
            dataUrl: '${apiIndex.f_Url}?'+ urlParams,
            isPage: true,
            isPost: false,
            reqData: "",
            columns: this.columns.reduce((acc, cur) => {
              acc[cur.label] = cur.prop;
              return acc;
            }, {}),
          };`);

          BTNSMETHODS.add(`   const url = await this.$awaitWraper(
            window.$axios({
              url: this.apiUrl + 'excel/export/exportfile',
              method: "post",
              data: params,
            })
          );
    
          if (url) {
            // 导出成功
            this.$downFile(url);
          } else {
            this.$message({
              type: "error",
              message: "导出失败",
            });
          }
    
          loading.close();`);

          BTNSMETHODS.add(`    
                 },`);
          break;
        default:
          BTNSMETHODS.add(`            handle${btn.prop}($index,row){`);
          BTNSMETHODS.add(`                console.log($index,row)// 在此处添加按钮逻辑`);
          BTNSMETHODS.add(`            },`);
          break;
      }
    });
  strCode = BTNSMETHODS.writeTo(strCode, "BTNSMETHODS");
  BTNSMETHODS = null;

  // 查询表单的数据列和列的转化数据列
  let DATACOMPUTED = new myString();

  let dataItemMap = {};
  let dataSourceMap = {};
  let apiDataSourceMap = {};
  dataOptions.forEach((item) => {
    let itemProp = "";
    if (mainTable.name == item.table) {
      itemProp = window.$lowerFirst(item.field);
    } else {
      itemProp = `${window.$lowerFirst(item.table)}_${item.field}`;
    }

    DATACOMPUTED.add(`            ${itemProp}Options(){`);
    switch (item.dataType) {
      case "1":
        // 1.静态数据
        DATACOMPUTED.add(`                return ${JSON.stringify(item.options)}`);
        break;
      case "2":
        // 2.数据字典数据
        dataItemMap[item.dataCode] = true;
        if (item.type == "treeselect") {
          DATACOMPUTED.add(`                return this.lr_dataItemTree(this.lr_dataItem['${item.dataCode}'])`);
        } else {
          DATACOMPUTED.add(`                return this.lr_dataItemOptions(this.lr_dataItem['${item.dataCode}'])`);
        }
        break;
      case "3":
        // 3.数据源数据
        dataSourceMap[item.dataCode] = true;
        if (item.type == "treeselect") {
          DATACOMPUTED.add(
            `                return this.lr_DataSourceTree(this.lr_dataSourceData['${item.dataCode}'],'${item.dataIdKey}','${item.dataPIdKey}','${item.dataValueKey}','${item.dataLabelKey}')`
          );
        } else {
          DATACOMPUTED.add(
            `                return this.lr_DataSourceOptions(this.lr_dataSourceData['${item.dataCode}'],'${item.dataValueKey}','${item.dataLabelKey}')`
          );
        }
        break;
      case "4":
        // 4.数据源数据
        apiDataSourceMap[item.apiCode] = item.apiUrl;
        if (item.type == "treeselect") {
          DATACOMPUTED.add(
            `                return this.lr_DataSourceTree(this.lr_apiDataSourceData['${item.apiCode}'],'${item.dataIdKey}','${item.dataPIdKey}','${item.dataValueKey}','${item.dataLabelKey}')`
          );
        } else {
          DATACOMPUTED.add(
            `                return this.lr_DataSourceOptions(this.lr_apiDataSourceData['${item.apiCode}'],'${item.dataValueKey}','${item.dataLabelKey}')`
          );
        }
        break;
    }
    DATACOMPUTED.add(`            },`);
  });
  strCode = DATACOMPUTED.writeTo(strCode, "DATACOMPUTED");
  DATACOMPUTED = null;

  let DATAINIT = new myString();
  for (let code in dataItemMap) {
    DATAINIT.add(`                this.lr_loadDataItem('${code}')`);
  }
  for (let code in dataSourceMap) {
    DATAINIT.add(`                this.lr_loadDataSourceData('${code}')`);
  }

  for (let code in apiDataSourceMap) {
    DATAINIT.add(`                this.lr_loadApiDataSourceData('${code}','${apiDataSourceMap[code]}')`);
  }

  strCode = DATAINIT.writeTo(strCode, "DATAINIT");
  DATAINIT = null;

  return strCode;
};
